package com.ghsc.ghxc.jsb.ui.my

import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.GridLayoutManager
import com.allen.library.shape.ShapeTextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.ext.gone
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.ext.visible
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.api.getUserIdRidUrl
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.FragmentMyBinding
import com.ghsc.ghxc.jsb.ext.copyToClipboard
import com.ghsc.ghxc.jsb.ui.home.activity.WebViewActivity
import com.ghsc.ghxc.jsb.ui.my.activity.AddressActivity
import com.ghsc.ghxc.jsb.ui.my.activity.FollowFansListActivity
import com.ghsc.ghxc.jsb.ui.my.activity.InvitePageActivity
import com.ghsc.ghxc.jsb.ui.my.activity.MyIntegralActivity
import com.ghsc.ghxc.jsb.ui.my.activity.MyTeamActivity
import com.ghsc.ghxc.jsb.ui.my.activity.OrderActivity
import com.ghsc.ghxc.jsb.ui.my.activity.RealNameAuthActivity
import com.ghsc.ghxc.jsb.ui.my.activity.SetUpActivity
import com.ghsc.ghxc.jsb.ui.my.bean.LocalCommonMenuBean
import com.ghsc.ghxc.jsb.ui.my.bean.LocalOrderMenuBean
import com.ghsc.ghxc.jsb.ui.my.bean.UserBeanData
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.my
 * 类名：MyFragment
 * 创建时间：2024/4/23 15:00
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class MyFragment : BaseVMFragment<MyViewModel, FragmentMyBinding>(R.layout.fragment_my){
    override fun attachVMClass(): Class<MyViewModel>? {
        return MyViewModel::class.java
    }

    override fun lazyLoad() {
    }

    override fun onResume() {
        super.onResume()
        mViewModel.onUserInfoMethod()
    }


    private var userInfo: UserBeanData?= null

    override fun initView(savedInstanceState: Bundle?) {
        initRefreshLayout()
    }


    override fun initData() {
        super.initData()
        //我的订单
        binding.rvOrder.layoutManager = GridLayoutManager(requireActivity(),5)
        binding.rvOrder.adapter = localOrderAdapter


        binding.rvCommon.layoutManager = GridLayoutManager(requireActivity(),4)
        binding.rvCommon.adapter = localCommonAdapter
        localCommonAdapter.setNewInstance(localCommonList())

    }

    private fun initRefreshLayout() {
        binding.refreshLayout.setEnableLoadMore(false)
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                mViewModel.onUserInfoMethod()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {

            }
        })
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@MyFragment) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(it)
            }
            againLoginMsg.observe(this@MyFragment) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }

            onUserInfoData.observe(this@MyFragment) {
                binding.refreshLayout.finishRefresh()
                userInfo = it.data.data
                GlideUtil.ImageHeadLoad(requireActivity(),it.data.data.headimg, binding.ivHeader)
                binding.tvName.text = it.data.data.nickname
                binding.tvPhone.text = "手机号：${it.data.data.mobile}"
                binding.tvInviteCode.text = "邀请码：${it.data.data.code}"
                it.data.data.zichan[0].forEach { (key, value) ->
                    binding.tvJiFen.text = value.toString()
                }
                it.data.data.zichan[1].forEach { (key, value) ->
                    binding.tvHaoYou.text = value.toString()
                }

                binding.tvFollow.text=it.data.data.follows.toString()
                binding.tvFans.text=it.data.data.fans.toString()


                //缓存个人信息
                UserManager.saveUserInfo(it.data.data)
                UserManager.setUserName(it.data.data.nickname)
                UserManager.setUserHead(it.data.data.headimg)
                localOrderAdapter.data.forEach { data->
                    if (data.name == "待付款"){
                        data.count = it.data.data.dfkcnt
                    }
                    if (data.name == "待发货"){
                        data.count = it.data.data.dfhcnt
                    }
                    if (data.name == "待收货"){
                        data.count = it.data.data.dshcnt
                    }
                    if (data.name == "已收货"){
                        data.count = it.data.data.yshcnt
                    }
                    if (data.name == "退换货"){
                        data.count = it.data.data.thhcnt
                    }
                }
                localOrderAdapter.notifyDataSetChanged()
            }
        }
    }


    override fun initClickListener() {
        super.initClickListener()
        binding.llBtnFollow.setSingleClickListener {
            //我的关注
            var bundle =Bundle()
            bundle.putInt("sign",1)
            startActivity(FollowFansListActivity().javaClass,bundle)
        }
        binding.llBtnFans.setSingleClickListener {
            //我的粉丝
            var bundle =Bundle()
            bundle.putInt("sign",2)
            startActivity(FollowFansListActivity().javaClass,bundle)
        }
        localOrderAdapter.setOnItemClickListener { adapter, view, position ->
            //我的订单跳转
            startKtxActivity<OrderActivity>(
                value = "position" to position
            )
        }
        localCommonAdapter.setOnItemClickListener { adapter, view, position ->
            val name = localCommonAdapter.data[position].name
            when (name) {
                "实名认证" -> {
                    startActivity(RealNameAuthActivity().javaClass)
                }
                "设置银行卡" -> {
                    val config = UserManager.getConfig()
                    config?.let {
                        var sysConfigResultData = it.getSysConfigBean(CustKey.configK3)
                        if(sysConfigResultData!=null)
                            if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                                requireActivity().startKtxActivity<WebViewActivity>(
                                    values = arrayListOf(
                                        "url" to sysConfigResultData.cfg_value+ getUserIdRidUrl(),
                                        "showBar" to false,
                                        "title" to sysConfigResultData.cfg_memo,
                                    )
                                )
                            }
                    }
                }
                "邀请好友" -> {
                    startActivity(InvitePageActivity().javaClass)
                }
                "地址管理" -> {
                    startActivity(AddressActivity().javaClass)
                }
                "招商中心" -> {
                    val config = UserManager.getConfig()
                    config?.let {
                        var sysConfigResultData = it.getSysConfigBean(CustKey.configK11)
                        if(sysConfigResultData!=null)
                        if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                            requireActivity().startKtxActivity<WebViewActivity>(
                                values = arrayListOf(
                                    "url" to sysConfigResultData.cfg_value+ getUserIdRidUrl(),
                                    "showBar" to true,
                                    "title" to sysConfigResultData.cfg_memo,
                                )
                            )
                        }else{
                            showToast("暂未开放，敬请期待")
                        }
                    }
                }
                "优惠券" -> {
                    showToast("暂未开放，敬请期待")
                }
                "设置" -> {
                    startActivity(SetUpActivity().javaClass)
                }
                "在线客服" -> {
                }
            }

        }
        binding.run {
            //查看全部订单
            tvAllOrder.setSingleClickListener {
                    startKtxActivity<OrderActivity>(
                        value = "position" to 0
                    )
            }
            //复制
            tvInviteCode.setSingleClickListener {
                userInfo?.let {
                    copyToClipboard(requireActivity(),it.code)
                }
            }
            //积分
            llYuanBao.setSingleClickListener {
                    startActivity(MyIntegralActivity().javaClass)
            }
            //好友
            llCoupon.setSingleClickListener {
                    startActivity(MyTeamActivity().javaClass)
            }
        }
    }

    //我的订单
    private val localOrderList = mutableListOf<LocalOrderMenuBean>().apply {
        add(LocalOrderMenuBean(R.drawable.ic_mine_menu_unpaid,"待付款"))
        add(LocalOrderMenuBean(R.drawable.ic_mine_menu_send,"待发货"))
        add(LocalOrderMenuBean(R.drawable.ic_mine_menu_wait,"待收货"))
        add(LocalOrderMenuBean(R.drawable.ic_mine_menu_received,"已收货"))
        add(LocalOrderMenuBean(R.drawable.ic_mine_menu_after_sale,"退换货"))
    }
    //我的订单
    private val localOrderAdapter = LocalOrderAdapter().apply {
        setNewInstance(localOrderList)
    }
    //我的订单
    inner  class LocalOrderAdapter  : BaseQuickAdapter<LocalOrderMenuBean, BaseViewHolder>(R.layout.layout_mine_menu_item) {

        override fun convert(helper: BaseViewHolder, item: LocalOrderMenuBean) {
            val stvCount = helper.getView<ShapeTextView>(R.id.stvCount)
            helper.setImageResource(R.id.ivMenu, item.icon)
                .setText(R.id.tvMenu, item.name)
            if (item.count > 0){
                stvCount.visible()
                stvCount.text = "${item.count}"
            }else {
                stvCount.gone()
            }
        }
    }

    //常用功能
    private val localCommonAdapter by lazy { LocalCommonAdapter() }
    private fun localCommonList(): MutableList<LocalCommonMenuBean> {
        var  localCommonList = mutableListOf<LocalCommonMenuBean>()
        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_renzheng,"实名认证"))
        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_bank,"设置银行卡"))
        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_invite,"邀请好友"))
        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_addresses,"地址管理"))
        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_agency,"招商中心"))
        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_coupon,"优惠券"))
        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_setup,"设置"))

//        localCommonList.add(LocalCommonMenuBean(R.drawable.ic_mine_menu_service,"在线客服"))
        return localCommonList
    }

    //常用功能
    inner class LocalCommonAdapter  : BaseQuickAdapter<LocalCommonMenuBean, BaseViewHolder>(
        R.layout.layout_mine_menu_item) {

        override fun convert(helper: BaseViewHolder, item: LocalCommonMenuBean) {
            helper.setImageResource(R.id.ivMenu, item.icon)
                .setText(R.id.tvMenu, item.name)
        }
    }

}